package com.fh.interceptor;

import com.fh.controller.system.weixin.wxutil.WeixinUtil;
import com.fh.entity.system.Menu;
import com.fh.entity.system.User;
import com.fh.service.contract.cuser.CUserService;
import com.fh.util.*;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 
* 类名称：LoginHandlerInterceptor.java
* 类描述： 
* @author FH
* 作者单位： 
* 联系方式：
* 创建时间：2015年1月1日
* @version 1.6
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter{
	protected Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private CUserService cUserService;
	private final String  authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		String path = request.getServletPath();
		logger.info("【path】"+path);
		if(path.matches(Const.PORTAL_INTERCEPTOR_PATH)){
			//shiro管理的session
			HttpSession session = request.getSession();
			Map<String, Object> pd= (Map<String, Object>) session.getAttribute(Const.SESSION_PORTAL_USER);
			//查看session中是否存在微信的用户信息
			if(pd==null){
				System.out.println("微信授权回调地址..");
				// 授权code
				String code = request.getParameter("code");
				if(code==null){
					String APPID = (String) MiceConfig.getContextProperty("wd_appID");
					String wd_URL = (String) MiceConfig.getContextProperty("wd_URL");
					String now_url = wd_URL + request.getContextPath() + path;
                    System.out.println(now_url+"转向的新地址");
					String URL = authorize_url.replace("APPID",APPID).replace("REDIRECT_URI",now_url);
					//跳转到关注微信号页面或提示
					System.out.println("code==null");
					response.sendRedirect(URL);
//					http://weixin.qq.com/r/PTiCmv-EvKLDrbv5920v
					return false;
				}else {
					//调取用户所有信息
					JSONObject map = WeixinUtil.getUserInfo(code);
					session.setAttribute("code", code);
					PageData userData = userData(map);

					//判断是否获取到了值
					if(userData.getString("OPEN_ID")==null || userData.getString("OPEN_ID").equals("")){
//						session.removeAttribute(Const.SESSION_PORTAL_USER);
//						String url="weixin_login";
//						response.sendRedirect(url);
						System.out.println("登录后直接跳转到首页");
						return false;
					}

					// 查询openid是否已存在
					PageData loginUser = cUserService.findByOpenId(userData);
					if (null == loginUser) {
						userData.put("ID", UuidUtil.get32UUID());
						//保存微信公众号openid和 binding_state 默认不开启
						cUserService.save(userData);
//						cUserService.save_reg_user(userData); 把绑定用户放到controller里面去
						PageData newUser = cUserService.findByOpenId(userData);
						session.setAttribute(Const.SESSION_PORTAL_USER, newUser);
						return true;
					}
					session.setAttribute(Const.SESSION_PORTAL_USER, loginUser);
				}

			}
			//fixme 判断微信用户表中 存在注册(手机号)签订人信息  如果不存在 就跳转到 绑定合同页面 如果存在就跳到我的
			PageData userData= new PageData();
			if(pd!=null){
				userData.put("OPEN_ID",pd.get("OPEN_ID"));
			}
			PageData loginUser = cUserService.findByOpenId(userData);
			if(loginUser!=null){
				PageData regdata=new PageData();
				regdata.put("OPEN_ID",loginUser.get("OPEN_ID"));
				List<PageData> regUser = cUserService.findByOpenId_reg(regdata);//已经绑定合同的用户数据
				if(regUser.size()<1){
					String url="weixin_login";
					response.sendRedirect(url);
					System.out.println("不存在数据的跳转");
					return false;
				}
			}else {
				//第一次登录没有获取到用户openid  获取不到用户信息 暂时重定向到 登录界面 如果存在用户信息 就直接登录
//				PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);

				/*String url="weixin_login";
				response.sendRedirect(url);*/
				return true;
			}


		}
		return true;
	}

	/**
	 * 组织用户数据
	 *
	 * @param jsonObject
	 * @return
	 */
	private PageData userData(JSONObject jsonObject) {
		PageData user = new PageData();
		if (null != jsonObject) {
			user.put("OPEN_ID", jsonObject.get("openid"));
			user.put("NICK_NAME", jsonObject.get("nickname"));
			user.put("SEX", jsonObject.get("sex"));
			user.put("LANAUAGE", jsonObject.get("language"));
			user.put("CITY", jsonObject.get("city"));
			user.put("PROVINCE", jsonObject.get("province"));
			user.put("COUNTRY", jsonObject.get("country"));
			user.put("PHOTO_URL", jsonObject.get("headimgurl"));
			user.put("SUBSCRIBE_TIME", new Date());
			user.put("UNIONID", jsonObject.get("unionid"));
			user.put("REMARK", jsonObject.get("remark"));
		}
		return user;
	}
	
}
